<template>
  <div class="registration-container">
    <!-- 标题区域 -->
    <div class="header">
      <h2>挂号订单</h2>
    </div>

    <!-- 基本查询条件区域 -->
    <div class="search-section">
      <h3>查询条件</h3>
      <el-form :model="queryForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="订单编号:">
              <el-input v-model="queryForm.orderNo" placeholder="请输入订单编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态:">
              <el-select v-model="queryForm.status" placeholder="全部" clearable>
                <el-option label="全部" value="" />
                <el-option
                    v-for="item in statuss"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="科室:"   >
              <el-input v-model="queryForm.departmentName" placeholder="请输入科室" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="就诊人:">
              <el-input v-model="queryForm.patientName" placeholder="请输入就诊人" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="button-group">
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="showAdvancedSearch = true">高级查询</el-button>
            <el-button @click="exportData">导出数据</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据列表区域 -->
    <div class="data-section">
      <div class="table-header">
        <h3>数据列表</h3>
        <div class="icon-buttons">
          <el-tooltip content="编辑" placement="top">
            <el-button :icon="Edit" circle plain @click="handleEdit" />
          </el-tooltip>
          <el-tooltip content="行列调整" placement="top">
            <el-button :icon="
            Operation" circle plain @click="handleColumnAdjust" />
          </el-tooltip>
          <el-tooltip content="刷新" placement="top">
            <el-button :icon="Refresh" circle plain @click="handleRefresh" />
          </el-tooltip>
          <el-tooltip content="设置" placement="top">
            <el-button :icon="Setting" circle plain @click="handleSettings" />
          </el-tooltip>
        </div>
      </div>
      <el-table :data="orderData" border style="width: 100%">
        <el-table-column prop="id" v-if="false" />
        <el-table-column prop="orderNo" label="订单编号" width="200" />
        <el-table-column prop="fee" label="挂号费用" width="120">
          <template #default="{row}">
            {{ row.fee }}元
          </template>
        </el-table-column>
        <el-table-column prop="patientName" label="就诊人" width="120" />
        <el-table-column prop="hospitalName" label="医院" width="180" />
        <el-table-column label="科室" width="180" >
          <template #default="{ row }">
            {{ row.departmentName }}
          </template>
        </el-table-column>
        <el-table-column prop="appointmentTime" label="下单时间" width="180" />
        <el-table-column  label="就诊日期" width="150">
          <template #default="scope">
            {{ scope.row.timePeriod }}:{{scope.row.startTime}}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{row}">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{row}">
            <el-button link type="primary" @click="viewDetails(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
          v-model="detailDialogVisible"
          title="订单详情"
          width="800px"
          custom-class="order-detail-dialog"
          center
      >
        <div class="order-detail-container">
          <div class="order-header">
            <h2>订单详情</h2>
            <div class="order-number">
              <strong>订单编号：</strong>{{ currentOrder.orderNo }}
            </div>
          </div>

          <div class="info-sections">
            <!-- 订单信息区域 -->
            <div class="info-section">
              <h2 class="section-title">订单信息</h2>
              <div class="info-grid">
                <div class="info-item">
                  <div class="info-label">下单时间</div>
                  <div class="info-value">{{ currentOrder.appointmentTime }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">挂号费用</div>
                  <div class="info-value">¥{{ currentOrder.fee }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">订单状态</div>
                  <div class="info-value">
                    <el-tag :type="getStatusTagType(currentOrder.status)" effect="light">
                      {{ getStatusText(currentOrder.status) }}
                    </el-tag>
                  </div>
                </div>

                <div class="divider-row"></div>

                <div class="info-item">
                  <div class="info-label">就诊医院</div>
                  <div class="info-value hospital-name">
                    <el-icon class="hospital-icon"><OfficeBuilding /></el-icon>
                    {{ currentOrder.hospitalName }}
                  </div>
                </div>

                <div class="info-item">
                  <div class="info-label">医院地址</div>
                  <div class="info-value">{{ currentOrder.address }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">医生姓名</div>
                  <div class="info-value">
                    <div class="doctor-name">{{ currentOrder.doctorName || '--' }}</div>
                    <div class="doctor-title">职称: {{ currentOrder.title }}</div>
                  </div>
                </div>

              </div>
            </div> <!-- 正确闭合 info-section -->

            <!-- 就诊人信息区域 -->
            <div class="info-section">
              <h2 class="section-title">就诊人信息</h2>
              <div class="info-grid">
                <div class="info-item">
                  <div class="info-label">患者姓名</div>
                  <div class="info-value">{{ currentOrder.patientName }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">电话</div>
                  <div class="info-value">{{ currentOrder.phone }}</div>
                </div>

                <div class="info-item">
                  <div class="info-label">就诊日期</div>
                  <div class="info-value time-highlight">
                    {{ currentOrder.scheduleDate }}:{{ currentOrder.timePeriod }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <template #footer>
          <el-button @click="detailDialogVisible = false">返回</el-button>
        </template>
      </el-dialog>
      <!-- 分页插件 ========================================== =============================== -->
      <div class="demo-pagination-block">
        <!--
                    1. current-page  ： 当前页   （重要）
                    2. page-size  : 每页显示条数（重要）
                    3. page-sizes ： 分页类型
                    4. small： 字体大小
                    5. disabled： 是否可用
                    6. background： 按钮颜色
                    7. total： 总数据条数（重要）

            -->
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[2, 3, 4, 5]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
      </div>
      <!-- 分页插件 ========================================== =============================== -->

    </div>

    <!-- 高级查询弹窗 -->
    <el-dialog v-model="showAdvancedSearch" title="高级查询" width="50%">
      <el-form :model="advancedQueryForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号:">
              <el-input v-model="advancedQueryForm.orderNo" placeholder="请输入订单编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医院名称:">
              <el-input v-model="advancedQueryForm.hospitalName" placeholder="请输入医院名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="就诊人姓名:">
              <el-input v-model="advancedQueryForm.patientName" placeholder="请输入就诊人姓名" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码:">
              <el-input v-model="advancedQueryForm.phone" placeholder="输入就诊人手机号码" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="一级科室:">
              <el-input v-model="advancedQueryForm.department" placeholder="请输入科室" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态:">
              <el-select v-model="advancedQueryForm.status" placeholder="请选择订单状态" clearable>
                <el-option label="全部" value="" />
                <el-option
                    v-for="item in statuss"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetAdvancedQuery">重置</el-button>
          <el-button type="primary" @click="handleAdvancedQuery">查询</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive, computed} from 'vue'
import { ElMessage } from 'element-plus'
import {Edit, OfficeBuilding, Operation, Refresh, Setting} from "@element-plus/icons-vue";
import axios from "axios";

const statuss=ref([])
const getStatuss=()=>{
  axios.get(`/appointmentRecord/getStatuss`).then(res=>{
    statuss.value=res.data.obj.map(item=>{
      return {
        label:item,
        value:item
      }
    })
  })
}

// 分页模型定义=======================================================================
let pageNum = ref(1);
let pageSize = ref(3);
let total = ref(1);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
}
const handleCurrentChange = (val) => {
  // 将这个val数字赋值给 pageNum
  pageNum.value = val;
  fetchData();
}
// 分页模型定义=======================================================================

// 获取数据==================================================================
const orderData = ref([])
const fetchData = () => {
  axios.get(`/appointmentRecord/getFetchData/${pageNum.value}/${pageSize.value}`).then(res=>{
    orderData.value = res.data.obj.data;
    total.value = res.data.obj.total;
    console.log(res.data.obj.data)
  })
}
// 获取数据==================================================================


// 获取状态显示文本========================================
const getStatusText = (status) => {
  const map = {
    unpaid: '未支付',
    paid: '已支付',
    canceled: '已取消'
  }
  return map[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  // 确保所有可能的订单状态都有对应的标签类型
  const map = {
    "未支付": "danger",
       // 英文状态也可以处理
    "已支付": "success",
    "paid": "success",        // 如果API返回英文状态
    "已取消": "info",
    "canceled": "info",
    "已完成": "primary"
  };

  // 确保不会返回空值
  return map[status] || "info";  // 设置默认值"info"避免空值
}
const queryForm = reactive({
  status:'',
  orderNo:'',
  fee:'',
  hospitalName:'',
  timePeriod: '',
  startTime: '',
  departmentName: '',
  patientName: ''
})

// 基本查询方法
const handleQuery = () => {
  // 构造符合Hospital对象的查询参数
  const searchParams = {
    status: queryForm.status,
    orderNo: queryForm.orderNo,
    fee:queryForm.fee,
    hospitalName: queryForm.hospitalName,
    timePeriod: queryForm.timePeriod,
    startTime: queryForm.startTime,
    departmentName: queryForm.departmentName,
    patientName: queryForm.patientName
  }
  axios.post(`/appointmentRecord/searchAppointmentRecord/${pageNum.value}/${pageSize.value}`, searchParams, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => {
    orderData.value = res.data.obj.data;
    total.value = res.data.obj.total;
    ElMessage.success('查询成功')
  }).catch(error => {
    ElMessage.error('查询失败: ' + error.message)
  })
}

// 重置基本查询
const resetQuery = () => {
  queryForm.value = {
    orderNo: '',
    status: '',
    departmentName: '',
    patientName: ''
  }
  fetchData()
}

// 高级查询方法
// 高级查询弹窗控制
const showAdvancedSearch = ref(false)
const handleAdvancedQuery = () => {
axios.post(`/appointmentRecord/searchAppointment/${pageNum.value}/${pageSize.value}`, advancedQueryForm.value, {
  headers: {
    'Content-Type': 'application/json'
  }
}).then(res => {
  orderData.value = res.data.obj.data;
  total.value = res.data.obj.total;
  ElMessage.success('查询成功')
  showAdvancedSearch.value = false
}).catch(error => {
  ElMessage.error('查询失败: ' + error.message)
})

}

// 重置高级查询
// 高级查询表单
const advancedQueryForm = ref({})

const resetAdvancedQuery = () => {
  advancedQueryForm.value = {
    orderNo: '',
    hospitalName: '',
    doctorName: '',
    patientName: '',
    phone: '',
    department: '',
    status: ''
  }
}

// 导出数据
const exportData = () => {
  location.href = "http://localhost:8080/appointmentRecord/download2"
  ElMessage.success('导出数据成功')
}




const handleEdit = () => {
  ElMessage.info('编辑功能')
  // 这里可以添加编辑逻辑
}

const handleColumnAdjust = () => {
  ElMessage.info('行列调整功能')
  // 这里可以添加列显示/隐藏控制逻辑
}

const handleRefresh = () => {
  ElMessage.success('数据已刷新')
  fetchData() // 重新获取数据
}

const handleSettings = () => {
  ElMessage.info('设置功能')
  // 这里可以打开设置对话框
}



const detailDialogVisible = ref(false)
const currentOrder = ref({})
// 获取订单详情
const getOrderDetail =(id) => {

axios.get(`/appointmentRecord/getOrderDetail/${id}`).then(res => {
  currentOrder.value = res.data.obj
  ElMessage.success('获取订单详情成功')
})
}

// 查看详情
const viewDetails = (row) => {
  console.log('当前行数据:', row); // 检查row对象

  getOrderDetail(row.id)
  detailDialogVisible.value = true
  ElMessage.info(`查看订单 ${row.orderNo} 的详情`)
}


onMounted(() => {
  fetchData();
  getStatuss();
})
</script>

<style scoped>
.registration-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  font-size: 20px;
  color: #333;
  font-weight: bold;
}

.search-section {
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-section h3 {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.data-section {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.data-section h3 {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.button-group {
  text-align: right;
  padding-right: 10px;
}

.el-table {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
/* 在style部分添加以下样式 */
.icon-buttons {
  display: flex;
  gap: 8px;
}

.icon-buttons .el-button {
  width: 32px;
  height: 32px;
  padding: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

/* 新增订单详情弹窗样式 */
.order-detail-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.order-detail-container {
  max-width: 100%;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
}

.order-header {
  padding: 24px 30px;
  background-color: #f8f9fb;
  border-bottom: 1px solid var(--border-color);
}

.order-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: var(--title-color);
  margin-bottom: 8px;
}

.order-number {
  font-size: 16px;
  color: var(--subtitle-color);
}

.order-number strong {
  color: var(--primary-color);
  margin-right: 5px;
}

.info-sections {
  padding: 30px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
}

.info-section {
  padding-bottom: 20px;
  border-bottom: 1px dashed var(--border-color);
}

.info-section:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.section-title {
  position: relative;
  padding-left: 15px;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
  color: var(--title-color);
}

.section-title:before {
  content: "";
  position: absolute;
  left: 0;
  top: 5px;
  bottom: 5px;
  width: 4px;
  background-color: var(--primary-color);
  border-radius: 2px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.info-item {
  padding: 8px 0;
}

.info-label {
  font-size: 14px;
  color: var(--subtitle-color);
  margin-bottom: 6px;
}

.info-value {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.divider-row {
  grid-column: 1 / -1;
  height: 1px;
  background-color: var(--border-color);
  margin: 15px 0;
}

.hospital-name {
  display: flex;
  align-items: center;
}

.hospital-icon {
  color: var(--primary-color);
  margin-right: 8px;
  font-size: 18px;
}

.doctor-info {
  display: flex;
  align-items: center;
}

.doctor-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-weight: bold;
  font-size: 18px;
}

.doctor-name {
  font-size: 16px;
  font-weight: 500;
}

.doctor-title {
  font-size: 14px;
  color: var(--subtitle-color);
}

.time-highlight {
  color: var(--primary-color);
  font-weight: bold;
  font-size: 16px;
}

/* 全局变量定义 */
:root {
  --primary-color: #409eff;
  --border-color: #dcdfe6;
  --title-color: #2d405e;
  --subtitle-color: #606266;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
}

</style>